import store from '@/store'
import AUTH_CODE from '@/config/auth'
function checkPermission(el, binding) {
  let { value } = binding
  const { permissionList, id } = store.getters && store.getters.roles
  value = value.map(item => {
    if (AUTH_CODE[item]) {
      return AUTH_CODE[item]
    } else if (item === 0) {
      return 0
    }
  })
  if (id === 1) return true
  if (value) {
    let hasPermission = null
    const permissionRoles = value
    if (value instanceof Array) {
      if (value.length > 0) {
        if (id === 0 && permissionRoles.includes(0)) {
          return true
        }
        hasPermission = permissionList.some(role => {
          return permissionRoles.includes(role)
        })
      }
    } else {
      hasPermission = permissionList.includes(permissionRoles)
    }
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`需要填写权限，比如这样： v-permission="['admin','editor']"`)
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
